﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using Lapkin.Attributes;
using Lapkin.Models.DataModels;
using Lapkin.Models.Repositories;

namespace Lapkin.Areas.Admin.Controllers
{
    [Authorize(Roles = "Admin")]
    public class PropertyController : Controller
    {
        private readonly SqlRepository _repository = new SqlRepository();
        public ActionResult Index()
        {
            return View();
        }

        [HttpPost, IsAjax]
        public JsonResult ListProperty()
        {
            IEnumerable<ProductProperty> properties = _repository.ProductRepository.GetListProductProperty();
            var fProperties =
                from p in properties
                select new
                    {
                        Id = p.Id,
                        Name = p.Name
                    };
            return Json(new { Result = "OK", Records = fProperties });
        }

        [HttpPost, IsAjax]
        public JsonResult AddProperty(ProductProperty property)
        {
            if (!ModelState.IsValid)
            {
                return Json(new { Result = "ERROR", Message = "Form is not valid! Please correct it and try again." });
            }

            ProductProperty productProperty = _repository.ProductRepository.CreateProductProperty(p => p.Name = property.Name);
            return productProperty != null ? 
                Json(new { Result = "OK", Record = productProperty }) : 
                Json(new { Result = "ERROR", Message = "Error" });
        }

        [HttpPost, IsAjax]
        public JsonResult UpdateProprty(ProductProperty property)
        {
            if (!ModelState.IsValid)
            {
                return Json(new {Result = "ERROR", Message = "Form is not valid! Please correct it and try again."});
            }
            _repository.ProductRepository.UpdateProductProperty(property);
            return Json(new { Result = "OK" });
        }

        [HttpPost, IsAjax]
        public JsonResult RemoveProperty(ProductProperty property)
        {
            if (!_repository.ProductRepository.RemoveProductProperty(property.Id))
            {
                return Json(new { Result = "ERROR", Message = "Error_delete" });
            }
            return Json(new {Result = "OK"});
        }
    }
}
